package com.kamfu.makingjavafunctional.example01;

import com.kamfu.function.common.Effect;
import com.kamfu.function.common.Function;
import com.kamfu.makingjavafunctional.Result02;

import java.util.regex.Pattern;

import static com.kamfu.function.common.Case.*;

/**
 * 用Case匹配条件
 */
public class EmailValidation06 {

    static Pattern emailPattern =
            Pattern.compile("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$");


    static Function<String, Result02<String>> emailChecker = s -> match(
            mcase(() -> Result02.success(s)),
            mcase(() -> s == null, () -> Result02.failure("email must not be null.")),
            mcase(() -> s.length() == 0, () ->
                    Result02.failure("email must not be empty.")),
            mcase(() -> !emailPattern.matcher(s).matches(), () ->
                    Result02.failure("email " + s + " is invalid."))
    );


    static Effect<String> success = s -> System.out.println("Verification mail sent to " + s);

    static Effect<String> error = s -> System.err.println("Error message logged: " + s);
    ;


    public static void main(String... args) {
        emailChecker.apply("this.is@my.email").bind(success, error);
        emailChecker.apply(null).bind(success, error);
        emailChecker.apply("").bind(success, error);
        emailChecker.apply("john.doe@acme.com").bind(success, error);
    }
}
